#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
    {
        dfs(root, p, q);
        return ans;
    }

private:
    bool dfs(TreeNode* node, TreeNode* p, TreeNode* q)
    {
        if (node == nullptr) return false;

        bool lson = dfs(node->left, p, q);
        bool rson = dfs(node->right, p, q);

        if ((lson && rson) || ((node == p || node == q) && (lson || rson)))
        {
            ans = node;
        }

        return (lson || rson) || (node == p || node == q);
    }

    TreeNode* ans = nullptr;
};